package org.ncibi.cytoscape.metscape.task;

import org.ncibi.metab.version.Version;
import org.ncibi.ws.HttpRequestType;
import org.ncibi.ws.Response;
import org.ncibi.ws.ResponseStatus;
import org.ncibi.ws.ResponseStatusType;
import org.ncibi.metab.ws.client.MetabolicVersionService;

import cytoscape.Cytoscape;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class GetVersionTask implements Task {

	public static final String TASK_TITLE = "Checking for Server Version";
	
	private JTaskConfig taskConfig = null;
	private Version serverVersion = null;
	private TaskMonitor monitor = null;
	
	public Version getServerVersion() {
		serverVersion = null;
		TaskManager.executeTask(this, getTaskConfig());
		return serverVersion;
	}
	
	@Override
	public void run() {
		monitor.setStatus("Contacting to server...");
		monitor.setPercentCompleted(-1);
		MetabolicVersionService versionService = new MetabolicVersionService(HttpRequestType.POST);
		monitor.setStatus("Checking status...");
		Response<Version> response = versionService.retrieveServerVersion();
		ResponseStatus responseStatus  = response.getResponseStatus();
		if (responseStatus.isSuccess())
			serverVersion = response.getResponseValue();
		else{
			String message = "Error: " + response.getResponseStatus().getMessage();
			if (response.getResponseStatus().getType().equals(ResponseStatusType.HTTP_ERROR)){
				int code = response.getResponseStatus().getHttpStatus().getStatusCode();
				message = "The server is not responding (status code = " + code + "). " +
						"If you know that this is transient error, try again later. Otherwise, " +
						"please contact metscape-help@umich.edu";
			}
			monitor.setException(null, message);
			serverVersion = null;
		}
		monitor.setPercentCompleted(100);
	}

	@Override
	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		this.monitor = monitor;
	}

	@Override
	public String getTitle() {
		return "Check for Server Version";
	}

	@Override
	public void halt() {
	}

	private JTaskConfig getTaskConfig() {
		if (taskConfig == null) {
		// Configure JTask Dialog Pop-Up Box
			taskConfig = new JTaskConfig();
			taskConfig.setOwner(Cytoscape.getDesktop());
			taskConfig.displayStatus(true);
		}
		return taskConfig;
	}
}
